package com.orderVideo.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.orderVideo.common.Result;
import com.orderVideo.dto.UpdatePasswordDTO;
import com.orderVideo.dto.UserPageDTO;
import com.orderVideo.entity.User;
import com.orderVideo.service.UserService;
import com.orderVideo.util.JwtUtil;
import com.orderVideo.utils.LoginUser;
import com.orderVideo.dto.UserInfoDTO;
import com.orderVideo.dto.UserMoneyDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


@Slf4j
@RestController
@RequestMapping("/api/user")
//@RequestMapping("/api2/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户注册
     * 注意：userImg字段应该包含Base64编码的图片数据
     * 示例格式："..."
     */
    @PostMapping("/register")
    public Result<User> register(@RequestBody User user) {
        try {
            User registeredUser = userService.register(user);
            return Result.success(registeredUser);
        } catch (Exception e) {
            log.error("用户注册失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 用户登录
     * @param user 包含用户名和密码的用户对象
     * @return token字符串
     */
    @PostMapping("/login")
    public Result<String> login(@RequestBody User user) {
        try {
            User loginUser = userService.login(user.getUsername(), user.getPassword());
            // 生成token
            String token = JwtUtil.generateToken(loginUser.getUserId());
            return Result.success(token);
        } catch (Exception e) {
            log.error("用户登录失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取用户金额信息，包括今日收益、账户余额和总收益
     * 
     * @return UserMoneyDTO 包含今日收益、账户余额和总收益的数据传输对象
     */
    @GetMapping("/getUserMoney")
    public Result<UserMoneyDTO> getUserMoney() {
        try {
            // 从全局上下文获取当前登录用户
            Long userId = LoginUser.getUserId();
            if (userId == null) {
                return Result.error("用户未登录");
            }
            UserMoneyDTO moneyDTO = new UserMoneyDTO();
            // 获取账户余额
            User user = userService.getById(userId);
            moneyDTO.setTotalEarnings(user.getTotalEarnings());
            moneyDTO.setAccountBalance(user.getUserMoney());
            moneyDTO.setTodayEarnings(user.getTodayEarnings());
            
            return Result.success(moneyDTO);
        } catch (Exception e) {
            log.error("获取用户金额信息失败", e);
            return Result.error("获取用户金额信息失败：" + e.getMessage());
        }
    }

    /**
     * 修改密码
     */
    @PostMapping("/password")
    public Result<Boolean> updatePassword(@RequestBody UpdatePasswordDTO dto) {
        try {
            boolean success = userService.updatePassword(dto);
            return Result.success(success);
        } catch (Exception e) {
            log.error("修改密码失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 更改别人密码
     * @param dto
     * @return
     */
    @PostMapping("/updateUserPassword")
    public Result<Boolean> updateUserPassword(@RequestBody UpdatePasswordDTO dto) {
        try {
            boolean success = userService.updateUserPassword(dto);
            return Result.success(success);
        } catch (Exception e) {
            log.error("修改密码失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 更新用户信息（头像和昵称）
     */
    @PostMapping("/update-info")
    public Result<Boolean> updateUserInfo(@RequestParam("file") MultipartFile file,
                                          @RequestParam("nickName") String nickName) {
        try {
            boolean success = userService.updateUserInfo(nickName, file);
            return Result.success(success);
        } catch (Exception e) {
            log.error("更新用户信息失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 管理员创建用户
     */
    @PostMapping("/admin/create")
    public Result<User> createUser(@RequestBody User user) {
        try {
            User createdUser = userService.createUser(user);
            return Result.success(createdUser);
        } catch (Exception e) {
            log.error("创建用户失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 管理员更新用户信息
     */
    @PutMapping("/admin/update")
    public Result<Boolean> updateUser(@RequestBody User user) {
        try {
            boolean success = userService.updateUser(user);
            return Result.success(success);
        } catch (Exception e) {
            log.error("更新用户失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 管理员删除用户
     */
    @DeleteMapping("/admin/{userId}")
    public Result<Boolean> deleteUser(@PathVariable Long userId) {
        try {
            boolean success = userService.deleteUser(userId);
            return Result.success(success);
        } catch (Exception e) {
            log.error("删除用户失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 管理员查询用户列表（分页）
     */
    @PostMapping("/admin/list")
    public Result<IPage<User>> getUserList(@RequestBody UserPageDTO pageDTO) {
        try {
            IPage<User> userPage = userService.getUserList(new Page<>(pageDTO.getPage(), pageDTO.getSize()));
            return Result.success(userPage);
        } catch (Exception e) {
            log.error("查询用户列表失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取用户信息
     */
    @GetMapping("/{userId}")
    public Result<User> getUserInfo(@PathVariable Long userId) {
        try {
            User user = userService.getById(userId);
            return Result.success(user);
        } catch (Exception e) {
            log.error("获取用户信息失败", e);
            return Result.error(e.getMessage());
        }
    }

    @GetMapping("/current")
    public Result<UserInfoDTO> getCurrentUserInfo() {
        try {
            // 获取当前登录用户ID
            Long userId = LoginUser.getUserId();
            User user = userService.getById(userId);
            if (user == null) {
                return Result.error("用户不存在");
            }
            // 转换为DTO
            UserInfoDTO userInfo = UserInfoDTO.fromUser(user);
            // 获取头像base64数据
            String avatarBase64 = userService.getAvatarBase64(user.getUserImg());
            userInfo.setAvatarBase64(avatarBase64);

            return Result.success(userInfo);
        } catch (Exception e) {
            return Result.error("获取用户信息失败：" + e.getMessage());
        }
    }
} 